package com.hzqx.syndata.hzqx;

import org.json.JSONObject;
import org.json.XML;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * @author yinzhiping
 */
@RestController
public class TestController {
    @Autowired
    RestTemplate restTemplate;

    /**
     * 尝试了几种办法  （1）getforObject得到的都是字符串格式，最后使用了exchange
     * @param stream
     */
    @RequestMapping("/provinceYjxx")
    public void getXmlProvinceYjxx(OutputStream stream){
        String url = "http://172.18.110.83:9093/alarms/xml/zj/gt/v1.0?appCode=35e972f934b7471eb16d9d94c73a1c78";
        //String data = restTemplate.getForObject(url,String.class);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Resource> httpEntity = new HttpEntity<Resource>(headers);
        byte[] data = restTemplate.exchange(url, HttpMethod.GET,httpEntity,byte[].class,"").getBody();
        try {
            stream.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用org.json.XML;提供的方法 将xml转化成json
     * @return
     */
    @RequestMapping("/pro")
    public String xmlToJson(){
        //https://base-api.zj121.com/alarms/xml/zj/gt/v1.0?appCode=35e972f934b7471eb16d9d94c73a1c78
        String url = "http://172.18.110.83:9093/alarms/xml/zj/gt/v1.0?appCode=35e972f934b7471eb16d9d94c73a1c78";
        String xml = restTemplate.getForObject(url,String.class);
        JSONObject xmlJSONObj = XML.toJSONObject(xml);
        return xmlJSONObj.toString();
    }

    /**
     * 访问的是省局的接口，下载一个json文件
     * @param type
     * @param num
     * @param request
     * @param response
     * @param stream
     */
    @RequestMapping("/{type}/{num}")
    public void downJson(@PathVariable("type") String type,@PathVariable("num") String num, HttpServletRequest request, HttpServletResponse response, OutputStream stream){
        System.out.println(type);

        String url = "http://pro-api-vpc.zj121.com/stms/qdh/latest/"+type+"/"+num+"?appCode=35e972f934b7471eb16d9d94c73a1c78";
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Resource> httpEntity = new HttpEntity<Resource>(headers);
        //byte[] data = restTemplate.exchange(url, HttpMethod.GET,httpEntity,byte[].class,"").getBody();
        //String url1 = "http://10.135.144.35:8090/ssny/cs1.jpg";
        ResponseEntity<byte[]> entity = restTemplate.exchange(url, HttpMethod.GET,new HttpEntity<>(headers), byte[].class);
        byte[] body = entity.getBody();
        /*OutputStream os = null;
        try {
            os = response.getOutputStream();
//          response.addHeader("Content-Type", "octet-stream");
            // 设置下载文件使用的报头
            response.setHeader("Content-Type", "application/x-download");
            response.setHeader("Content-Disposition", "attachment; filename="+ toUTF8String(type+"_"+num+".json"));
            os.write(body);
            os.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }*/
        try {
            stream.write(body);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * 下载保存时中文文件名的字符编码转换方法
     */
    public String toUTF8String(String str) {
        StringBuffer sb = new StringBuffer();
        int len = str.length();
        for (int i = 0; i < len; i++) {
            // 取出字符中的每个字符
            char c = str.charAt(i);
            // Unicode码值为0~255时，不做处理
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else { // 转换 UTF-8 编码
                byte b[];
                try {
                    b = Character.toString(c).getBytes("UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    b = null;
                }
                // 转换为%HH的字符串形式
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) {
                        k &= 255;
                    }
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }

    /**
     * 下载文件
     * @param response
     * @throws IOException
     */
    @RequestMapping("getfile")
    public void getFile(HttpServletResponse response) throws IOException {
        OutputStream outputStream = response.getOutputStream();
        //读取一个文件
        //第一种方法：用FileInputStream
        //FileInputStream fileInputStream = new FileInputStream("D:/data/123.jpg");

        //第二种方法
        //使用file读取
        File file = new File("D:/data/123.jpg");
        FileInputStream fileInputStream = new FileInputStream(file);
        try {

            byte[] buf = new byte[1024]; //数据中转站 临时缓冲区
            int length = 0;
            //循环读取文件内容，输入流中将最多buf.length个字节的数据读入一个buf数组中,返回类型是读取到的字节数。
            //当文件读取到结尾时返回 -1,循环结束。
            while((length = fileInputStream.read(buf)) != -1){
               outputStream.write(buf,0,length);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                fileInputStream.close();//强制关闭输入流
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("outfile")
    public void writeFile() throws IOException {
        File file = new File("D:\\d.txt");
        //创建文件字节输出流对象，准备向d.txt文件中写出数据,true表示在原有的基础上增加内容
        FileOutputStream fout=new FileOutputStream(file,true);
        Scanner sc=new Scanner(System.in);
        System.out.println("请写出一段字符串:");
        String msg=sc.next()+"\r\n";;
        /******************(方法一)按字节数组写入**********************/
        //msg.getBytes()将字符串转为字节数组
        //byte[] bytes = msg.getBytes();
        //使用字节数组输出到文件
        //fout.write(bytes);

        //(方法2)逐字节写入
        byte[] bytes = msg.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            //逐字节写文件
            fout.write(bytes[i]);
        }
        fout.flush();//强制刷新输出流
        fout.close();//关闭输出流

        InputStream in=new FileInputStream(new File("F:\\t.txt"));
    }

    @RequestMapping("/fb")
    public void getTxtProvinceFb(OutputStream stream){
        String url = "http://172.18.110.84:8089/hangzhou-app/nowcasting/rada/txt?appCode=ec827e32357c49fb864b752e2d4ef138";
        //String data = restTemplate.getForObject(url,String.class);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Resource> httpEntity = new HttpEntity<Resource>(headers);
        byte[] data = restTemplate.exchange(url, HttpMethod.GET,httpEntity,byte[].class,"").getBody();
        try {
            stream.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/fb2")
    public void downFbTxt( HttpServletRequest request, HttpServletResponse response, OutputStream stream){

        String url = "http://172.18.110.84:8089/hangzhou-app/nowcasting/rada/txt?appCode=ec827e32357c49fb864b752e2d4ef138";
        URL url1 = null;
        URLConnection con = null;
        try {
            url1 = new URL(url);
            con = url1.openConnection();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String fieldValue = con.getHeaderField("Content-Disposition");
        if (fieldValue == null || ! fieldValue.contains("filename=\"")) {

        }
        String filename = fieldValue.substring(fieldValue.indexOf("filename=\"") + 10, fieldValue.length() - 1);
        //System.out.println(filename);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Resource> httpEntity = new HttpEntity<Resource>(headers);
        ResponseEntity<byte[]> entity = restTemplate.exchange(url, HttpMethod.GET,new HttpEntity<>(headers), byte[].class);
        byte[] body = entity.getBody();

        OutputStream os = null;
        try {
            os = response.getOutputStream();
//          response.addHeader("Content-Type", "octet-stream");
            // 设置下载文件使用的报头
            response.setHeader("Content-Type", "application/x-download");
            response.setHeader("Content-Disposition", "attachment; filename="+ toUTF8String(filename));
            os.write(body);
            os.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public void downFbTxt(HttpServletResponse response) throws IOException {
        String url = "http://172.18.110.84:8089/hangzhou-app/nowcasting/rada/txt?appCode=ec827e32357c49fb864b752e2d4ef138";
        URL url1 = null;
        URLConnection con = null;
        url1 = new URL(url);
        con = url1.openConnection();
        String fieldValue = con.getHeaderField("Content-Disposition");
        if (fieldValue == null || ! fieldValue.contains("filename=\"")) {

        }
        String filename = fieldValue.substring(fieldValue.indexOf("filename=\"") + 10, fieldValue.length() - 1);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Resource> httpEntity = new HttpEntity<Resource>(headers);
        ResponseEntity<byte[]> entity = restTemplate.exchange(url, HttpMethod.GET,new HttpEntity<>(headers), byte[].class);
        byte[] body = entity.getBody();
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            response.setHeader("Content-Type", "application/x-download");
            response.setHeader("Content-Disposition", "attachment; filename="+ toUTF8String(filename));
            os.write(body);
            os.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
